import sys
import time
from coin2.api_client.binance import BinancePrivateClient
from coin.proto.coin_query_pb2 import FundingFeeBundle
from cc.appcoin2.support.symbology.py_symbology import PyProduct

class BinanceFundingFee():
  def __init__(self, key_path: str, mea: str, ip=None):
    self.binance = BinancePrivateClient(key_path, mea, ip)

  def get_funding_fee(self, start_timestamp: int, end_timestamp: int, limit: int = 1000) -> FundingFeeBundle:
    json = self.binance.get_funding_fee(start_timestamp, end_timestamp, limit)

    funding_fees = FundingFeeBundle()

    mea_array = self.binance._mea.split(".")
    mea_str = self.binance._mea.replace(".", ":")

    funding_fees.exchange = mea_array[1]
    funding_fees.market_type = mea_array[0]

    resolve_timestamp = time.time_ns()

    for record in json:
      funding_fee = funding_fees.each_funding_fee.add()

      symbol = PyProduct.from_native(f"{mea_str}:{record['symbol']}", resolve_timestamp)

      if record["asset"] == symbol.base.native_currency:
        currency = symbol.base
      elif record["asset"] == symbol.quote.native_currency:
        currency = symbol.quote
      else:
        assert False, f"Unexpected asset:{record['asset']}!"

      funding_fee.id = str(record["tranId"])
      funding_fee.symbol = symbol.symbol
      funding_fee.funding_fee = -float(record["income"])
      funding_fee.funding_fee_currency = currency.currency
      funding_fee.timestamp = record["time"] * 1000000

    return funding_fees

if __name__ == "__main__":
  key_path = sys.argv[1]
  config = {}
  config["key_path"] = key_path

  binance = BinanceFundingFee(key_path, "Futures.Binance.v1")
  resp = binance.get_funding_fee(1693191443000000000, 1693220243000000000, 1000)

  print(resp)
